<?php
defined('IN_LK') or die('Access Denied');
lk::lo('session_' . SESSION_STORAGE);
class index
{
	public function __construct()
	{
		
	}
	
	public function initialize()
	{
		
	}
	
	/**
	 * 图像化字符
	 */
	public function toimage()
	{
		$str = isset($_GET['i']) ? $_GET['i'] : '';
		lk::lo_app('image', 'api', 0);
		$image = new image($str);
		$image->output();
	}
	
	/**
	 * 验证码输出
	 */
	public function captcha()
	{
		lk::lo_app('captcha', 'api', 0);
		$captcha = new captcha(90, 28);
		$captcha->output();
	}
	
	/**
	 * 检查验证码是否正确
	 * @return output 正确1 错误0
	 */
	public function check_captcha_ajax()
	{
		$captcha = isset($_GET['captcha']) && $_GET['captcha'] ? $_GET['captcha'] : '';
		strtolower($captcha) == strtolower($_SESSION['captcha']) ? exit('1') : exit('0');
	}
	
	public function upload()
	{
		//TODO 使用attachment 类完成加水印存数据库等动作，由于时间关系，我不做了
		$err = 0;
		$catid = isset($_POST['catid']) ? (int)$_POST['catid'] : 1;
		if(isset($_FILES['filedata']))
		{
			$files = $_FILES['filedata'];
			switch($files['error'])
			{
				case 0:
					break;
				default:
					$err = 1;
					break;
			}
			if(is_uploaded_file($files['tmp_name']))
			{
				$ext  = fileext($files['name']);
				$size = $files['size'];
				$name = date('Ymdhis', TIME) . mt_rand(100, 999) . '.' . $ext;
				if(!preg_match("/^(" . ALLOW_EXT . ")\$/", $ext))
				{
					$err = 2;
				}
				else if($size> UPLOAD_MAXSIZE)
				{
					$err = 3;
				}
				else
				{
					$dst_dir  = UPLOAD_PATH . $catid . DIRECTORY_SEPARATOR;
					$dst_file = $dst_dir . $name;
					$img = str_replace(DIRECTORY_SEPARATOR, '/', str_replace(UPLOAD_PATH, '', $dst_file));
					if(!is_dir($dst_dir))
					{
						mkdir($dst_dir, 0777);
					}
					if(!move_uploaded_file($files['tmp_name'], $dst_file))
					{
						$err = 4;
						break;
					}
					else
					{
						//TODO 生成一张小的缩略图
					}
				}
			}
			else
			{
				$err = 5;
			}
		}
		else
		{
			$err = 6;
		}
		$jquery = '<script type="text/javascript" src="' . JS_PATH . 'jquery.1.5.1.js"></script>';
		if($err)
		{
			exit($jquery . "<script type=\"text/javascript\">"
		   . "alert('上传文件类型或大小不正确');"
		   . "</script>");
		}
		else
		{
			exit($jquery . "<script type=\"text/javascript\">"
           . "parent.showimg('" . $img . "')"
		   . "</script>");
		}
	}
	
	public function download()
	{
		
	}
}